package com.atguigu.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * projectName: day04_jdbc
 *
 * @author: 赵伟风
 * time: 2021/11/26 15:17
 * description: 使用动态的statement
 *    todo 模拟登录案例
 *    CREATE TABLE USER(
 *    id INT PRIMARY KEY AUTO_INCREMENT,
 *    nickname VARCHAR(20),
 *    account VARCHAR(20) NOT NULL UNIQUE,
 *    PASSWORD VARCHAR(20) NOT NULL
 * )
 */
public class JdbcCrud {


    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql:///test1", "root", "root");

        //3.创建预编译statement
        //结构sql语句！ 值的部分用 ? 号代替！ ? 占位符的意思
        String  sql = "select * from user where account = ? and password = ?;";

        PreparedStatement statement = connection.prepareStatement(sql);

        //4.占位符赋值
        /**
         * 参数1： ?的下角标 从1开始 从左开始
         */
        System.out.println("请您输入账号！");
        Scanner scanner = new Scanner(System.in);
        String account =  scanner.nextLine();
        System.out.println("请您输入密码！");
        String pwd = scanner.nextLine();
        statement.setObject(1,account);
        statement.setObject(2,pwd);


//        FileInputStream fileInputStream  = null;
//        statement.setObject(3,fileInputStream);
        //5.执行sql语句！ 不需要在指明sql语句了
        ResultSet resultSet = statement.executeQuery();


        // sql 关键字 函数 容器名  `字符`  `order`

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();


        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {

                String string = resultSet.getString(i);

                System.out.println("string = " + string);
            }
        }

        //7.关闭资源

        resultSet.close();

        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }

}
